<?php
include(dirname(__FILE__)."/../../global.php");
include(INCLUDE_PATH."common/common.func.php");

$strTimerFile = SQL_LOG_PATH . "timer.log";
$strErrorFile = SQL_LOG_PATH . "error.log";
$strCommandLog = SQL_LOG_PATH . "command.log";

$base_dir = SQL_LOG_PATH . "data/";
$error_dir = SQL_LOG_PATH . "error/";

if(!is_dir($error_dir)) {
	$shell = "mkdir -p ".$error_dir;
	shell_exec($shell);
}

while(true) {
	$backup_dir = SQL_LOG_PATH."backup/".date("Ym")."/".date("d")."/";

	if(!is_dir($backup_dir)) {
		$shell = "mkdir -p ".$backup_dir;
		shell_exec($shell);
	}

	$statTime = time();
	if (is_dir($base_dir) && $handle = opendir($base_dir)) {
		$arrLogFile = array();
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != ".." && $file != ".svn") {
				$filename       = $base_dir."".$file;
				$type           = (is_dir($filename)) ? "dir" : "file";

				if($type == "file") {
					$arrFile		= explode("_",$file);
					
					$iMinute		= date("i");

					$iLogMinute = sprintf("%s0",floor($iMinute / 10));

					$iCurrentDate	= date("YmdH") . $iLogMinute;
					
					if(isset($arrFile[0]) && $arrFile[0] < $iCurrentDate) {
						$strCommand = MYSQL_PATH . " -h".DB_LOG_HOST." -u".DB_LOG_USER." -p".DB_LOG_PASS." -e \"use ".DB_LOG_NAME.";source ".$filename.";\" > ".$strCommandLog."";

						//echo $strCommand."\n";

						passthru($strCommand,$status);
						if($status == 0) {
							@unlink($filename);
							$fp = fopen($strTimerFile,"w");
							fwrite($fp,$strCommand."\n");
							fclose($fp);
						} else {
							shell_exec("mv ".$filename . " " . $error_dir.$file);
							@unlink($filename);
							$fp = fopen($strErrorFile,"a");
							fwrite($fp,$strCommand . "\n");
							fclose($fp);
						}
						//array_push($arrLogFile,$strCommand);
					}
				}
			}
		}

		closedir($handle);
	}
	$iSleepTime = rand(300000000,600000000);
	usleep($iSleepTime);
}
exit;
?>